//
//  HSYCustomArcView+Animation.m
//  CustomNavigationController
//
//  Created by key on 2017/2/22.
//  Copyright © 2017年 huangsongyao. All rights reserved.
//

#import "HSYCustomArcView+Animation.h"
#import "HSYCustomArcLayer.h"

#define DEFAULT_ANIMATION_DURATION      0.5f

@implementation HSYCustomArcView (Animation)

+ (CABasicAnimation *)animationByKeyPath:(NSString *)key animationDuration:(NSTimeInterval)duration toValue:(CGFloat)value delegate:(id<CAAnimationDelegate>)delgate
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:key];
    animation.duration = duration;
    animation.toValue = @(value);
    animation.removedOnCompletion = YES;
    animation.fillMode = kCAFillModeForwards;
    animation.delegate = delgate;
    
    return animation;
}

- (void)addArcAnimationByKeyPath:(NSString *)key animationDuration:(NSTimeInterval)duration toValue:(CGFloat)value delegate:(id<CAAnimationDelegate>)delgate
{
    CABasicAnimation *animation = [self.class animationByKeyPath:key
                                               animationDuration:duration
                                                         toValue:value
                                                        delegate:delgate];
    [self.arcLayer addAnimation:animation forKey:[key stringByAppendingString:key]];
}

- (void)addArcAnimationByDuration:(NSTimeInterval)duration toValue:(CGFloat)value
{
    [self addArcAnimationByKeyPath:PROGRESS_PROPERTY animationDuration:duration toValue:value delegate:self];
}

- (void)addArcAnimationToValue:(CGFloat)value
{
    [self addArcAnimationByDuration:[self.class readDurationByValue:value] toValue:value];
}

+ (NSTimeInterval)readDurationByValue:(CGFloat)value
{
    CGFloat multiple = 1.0;
    NSTimeInterval times = 0;
    if (value >= 0 && value <= multiple/4) {
        times = DEFAULT_ANIMATION_DURATION;
    } else if (value > multiple/4 && value <= multiple/2) {
        times = DEFAULT_ANIMATION_DURATION *2;
    } else if (value > multiple/2 && value <= multiple/4*3) {
        times = DEFAULT_ANIMATION_DURATION *3;
    } else {
        times = DEFAULT_ANIMATION_DURATION *4;
    }
    return times;
}

#pragma mark - CAAnimationDelegate

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (flag) {
        self.arcLayer.progress = self.progress;
    }
}

@end
